<meta charset="UTF-8">
<meta name="Viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"/>
<div id="app">
    <input placeholder="点击换行保存" type="text" v-model="title" @keydown.enter="addTodo">
    <button v-if="active<all" @click="clear">清理</button>
    <ul>
        <li v-for="todo in todos">
            <input type="checkbox" v-model="todo.done">
            <span :class="{done:todo.done}"> {{todo.title}}</span>
        </li>
    </ul>
    <div>
        全选<input type="checkbox" v-model="allDone">
        <br>
        <span> {{active}}  / {{all}} </span>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@next"></script>
<script>
    const KEY = 'TODOS'
    const App = {
        data() {
            return {
                title: "", // 定义一个数据
                todos:[
                    {title:'待办事项1',done:false},
                ]
            }
        },
        methods:{
            addTodo(){
                this.todos.push({
                    title:this.title,
                    done:false
                })
                this.title = ""
                localStorage.removeItem(KEY)
                localStorage.setItem(KEY, JSON.stringify(this.todos))
            },
            clear(){
                this.todos = this.todos.filter(v=>!v.done)
            }
        },
        computed:{
            active(){ return this.todos.filter(v=>!v.done).length },
            all(){ return this.todos.length },
            allDone: {
                get: function () { return this.active === 0 },
                set: function (val) { this.todos.forEach(todo=>{ todo.done = val }); }
            }
        },
        mounted() {
            const v = localStorage.getItem(KEY)
            if (v) {
                this.todos = [...JSON.parse(v)]
            }

        },
        watch: {
            todos: {//监听数据变更
                handler(newVal, oldVal) {
                    console.info("todos->change")
                    localStorage.setItem(KEY, JSON.stringify(this.todos))
                },
                deep: true
            }
        },
    }
    // 启动应用
    Vue.createApp(App).mount('#app')
</script>
<style>
    .done{
        color:gray;
        text-decoration: line-through;
    }
</style>
